﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;

namespace RPGXEngine
{
    public class Logger : ILogger
    {
        #region Properties

        public static object Lock = new object();

        public string LogPath
        {
            get { return this._logPath; }
            set { this._logPath = value; }
        }
        private string _logPath = String.Empty;

        public FileStream Fs
        {
            get { return this._fs; }
            set { this._fs = value; }
        }
        private FileStream _fs = null;

        #endregion

        #region Public Mehtods

        public void Log(string message)
        {
            lock (Logger.Lock)
            {
                this.OpenLog(this.LogPath);

                StreamWriter sw = new StreamWriter(this.Fs);

                sw.WriteLine(String.Format("{0:dd:mm:yyy hh:MM:ss.ff} ({1}): {2}",
                    DateTime.Now,
                    Thread.CurrentThread.ManagedThreadId,
                    message));

                sw.Flush();
                sw.Close();

                this.CloseLog();
            }
        }

        #endregion

        #region Private Methods

        private void CloseLog()
        {
            if (this.Fs == null)
                return;

            this.Fs = null;
        }

        private void OpenLog(string path)
        {
            if (this.Fs != null)
                this.CloseLog();

            try
            {
                this.Fs = File.Open(path, FileMode.Append, FileAccess.Write);
            }
            catch (Exception)
            {
                // log it...? lol. No really, have a base definate log
            }
        }

        #endregion
    }
}
